package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class UploadService {

    private static final String IMAGE_DIR = "C:\\lesson\\heima75\\nginx-1.12.2\\html\\images";

    private static final String IMAGE_URL = "http://image.leyou.com/images/";

    private static final List<String> ALLOW_IMAGE_TYPES = Arrays.asList("image/jpeg", "image/png", "image/bmp");

    public String uploadBrandImage(MultipartFile file) {
        try {
            // 0.文件后缀名校验
            String contentType = file.getContentType();
            if(!ALLOW_IMAGE_TYPES.contains(contentType)){
                throw new RuntimeException("文件类型有误！");
            }
            // 1.获取图片名称
            String originalFilename = file.getOriginalFilename();
            String extension = StringUtils.substringAfterLast(originalFilename, ".");
            String filename = UUID.randomUUID().toString() + "." + extension;

            // 2.获取图片存储路径
            File path = new File(IMAGE_DIR, filename);

            // 3.保存图片
            try {
                file.transferTo(path);
            } catch (IOException e) {
                throw new RuntimeException("文件保存失败！");
            }

            // 4.返回图片的可访问地址
            return IMAGE_URL + filename;
        } catch (RuntimeException e) {
            log.error("文件上传失败，原因：{}", e.getMessage());
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR, e);
        }
    }

    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS client;

    public Map<String, Object> getSignature() {
        try {
            // 1.计算签名
            // 1.1.超时时间
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // 1.2.文件上传条件限制
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 1.3.加密文件限制条件
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 1.4.生成签名
            String postSignature = client.calculatePostSignature(postPolicy);

            // 2.封装结果
            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            // 3.返回
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
